package com.author.document.view;

import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;

import javax.swing.text.BoxView;
import javax.swing.text.Element;
import javax.swing.text.ParagraphView;
import javax.swing.text.View;

import com.author.document.model.ExtendedDocument;

public class ExtendedParagraphView extends ParagraphView {
	/* DELTA is used to adjust the width of the paragraph view */
	private float	DELTA	= (float) 0.0;

	public ExtendedParagraphView(Element arg0) {
		super(arg0);
	}

	@Override
	public float getPreferredSpan(int axis) {
		if (axis == View.Y_AXIS) {
			return super.getPreferredSpan(axis);
		}
		return super.getPreferredSpan(axis) - this.DELTA;
	}

	@Override
	public void paint(Graphics g, Shape alloc) {
		Element e = this.getElement();
		float pDELTA = this.DELTA;
		DELTA = (float) (e.getAttributes().getAttribute(
				ExtendedDocument.PARAGRAPH_LEFT_INSET) == null ? 0.0
				: (Float) e.getAttributes().getAttribute(
						ExtendedDocument.PARAGRAPH_LEFT_INSET));

		/* If the value of the left inset has not changed then just repaint */
		if ((DELTA == (float) 0.0) || (pDELTA == DELTA)) {
			super.paint(g, alloc);
			return;
		}

		/*
		 * When the left insets are set or reset then we paint the entire text
		 * component as a result of which the extended paragraph view will get
		 * painted again
		 */
		short left_inset = (short) (this.getLeftInset() + DELTA < 0 ? 0 : this
				.getLeftInset() + DELTA);
		this.setInsets(getTopInset(), (short) (left_inset), getBottomInset(),
				getRightInset());
		this.getParent().preferenceChanged(this, true, false);
		this.getContainer().repaint();
	}
}
